/**
 * @projectName: LeetCode
 * @package: PACKAGE_NAME
 * @className: Point4
 * @author: Mocrash
 * @description: TODO
 * @date: 2024/10/16 11:25
 * @version: 1.0
 */
public class Point4 {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums1 = new int[]{1, 2};
        int[] nums2 = new int[]{2};
        double medianSortedArrays = solution.findMedianSortedArrays(nums1, nums2);
        System.out.println("中位数是: " + medianSortedArrays);
    }

    private static class Solution {
        public double findMedianSortedArrays(int[] nums1, int[] nums2) {
            int[] mergeArr = merge(nums1, nums2);
            int mind = (mergeArr.length - 1) / 2;
            double returner = 0.0;
            if (mergeArr.length % 2 == 0) {
                returner = ((double) mergeArr[mind] + (double) mergeArr[mind + 1]) / 2;
            } else {
                returner = (double) mergeArr[mind];
            }
            return returner;

        }

        private static int safeAverage(int A, int B) {
            //(A+B)/2不会溢出的写法
            return (A & B) + ((A ^ B) >> 1);
        }

        private int[] merge(int[] nums1, int[] nums2) {
            if ((nums1 == null || nums1.length == 0) && nums2 != null) return nums2;
            if (nums2 == null || nums2.length == 0) return nums1;
            int[] res = new int[nums1.length + nums2.length];
            int i = 0, j = 0, resIndex = 0;
            while (i < nums1.length && j < nums2.length) {
                res[resIndex] = nums1[i] < nums2[j] ? nums1[i++] : nums2[j++];
                resIndex += 1;
            }
            while (i < nums1.length) {
                res[resIndex++] = nums1[i++];
            }
            while (j < nums2.length) {
                res[resIndex++] = nums2[j++];
            }
            return res;
        }
    }

}

